package com.greenline.push.common.cookie;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.greenline.framework.mursi.web.module.cookie.CookieModule;
import com.greenline.push.common.constants.GlobalConstants;

/**
 * @Type UserCookieUtil
 * @Desc 用户信息的cookie操作工具类
 * @author weirui.shenwr
 * @date 2012-3-21
 * @Version V1.0
 */
public class UserCookieUtil extends CookieUtil {
    private static final Log logger = LogFactory.getLog(UserCookieUtil.class);

    /** 配置的用户id */
    public static final String USER_ID = "userId";
    /** 配置的用户昵称 */
    public static final String NICK_NAME = "nickName";
    /** 配置的登入ID */
    public static final String LOGIN_ID = "loginId";

    /** cookie中设置的长session id **/
    public static final String PER_SEEEIONID = "sessionId";

    /** 用户类型 */
    public static final String USER_TYPE = "userType";

    // 机构
    public static final String INSTITUTION = "institution";
    // 机构名称
    public static final String INSTITUTIONNAME = "institutionName";

    // 账户号
    public static final String ACCOUNTNO = "accountNo";

    /**
     * id+"|"+name
     * 
     * @param request
     * @return
     */
    public static String getOperatorForSave(HttpServletRequest request) {
        Long id = getUserId(request);
        if (id == null) {
            return "";
        }
        return id + "|" + getNickName(request);
    }

    /**
     * 设置用户信息到cookie
     * 
     * @param request
     * @param user
     * @param expiry
     */
    public static void write(HttpServletRequest request, CookieUser user) {

        if (request == null || user == null) {
            throw new IllegalArgumentException();
        }
        CookieModule jar = getCookieModule(request);
        if (jar == null) {
            throw new NullPointerException();
        }
        // 用户ID
        jar.set(USER_ID, user.getUserId());
        jar.set(USER_TYPE, user.getUserType());
        try {
            // loginId和nickname有中文必须encode如果为空必须移除原始数据
            if (StringUtils.isNotBlank(user.getLoginId())) {
                jar.set(LOGIN_ID, URLEncoder.encode(user.getLoginId(), GlobalConstants.CHARACTER_ENCODING));
            } else {
                jar.remove(LOGIN_ID);
            }
            if (StringUtils.isNotBlank(user.getNickName())) {
                jar.set(NICK_NAME, URLEncoder.encode(user.getNickName(), GlobalConstants.CHARACTER_ENCODING));
            } else {
                jar.remove(NICK_NAME);
            }

        } catch (UnsupportedEncodingException e) {
        }
    }

    /**
     * 通过cookie中是否有userId判断用户是否登入
     * 
     * @param request
     * @return boolean true是，false否
     */
    public static boolean isLogin(HttpServletRequest request) {
        Long userId = getUserId(request);
        if (userId != null) {
            return true;
        }
        return false;
    }

    /**
     * 清除cookie里的所有用户信息
     * 
     * @param request
     */
    public static void clear(HttpServletRequest request) {
        CookieModule jar = getCookieModule(request);
        if (jar != null) {
            jar.remove(USER_ID);
            jar.remove(NICK_NAME);
            jar.remove(LOGIN_ID);
            jar.remove(USER_TYPE);
            jar.remove(INSTITUTION);
            jar.remove(INSTITUTIONNAME);
        }
    }

    /**
     * 获取用户的user_id
     * 
     * @param request
     * @return Long
     */
    public static Long getUserId(HttpServletRequest request) {
        String idStr = getCookieValue(request, USER_ID);
        if (StringUtils.isNumeric(idStr)) {
            return Long.valueOf(idStr);
        }
        return null;
    }

    /**
     * 获取用户NickName
     * 
     * @param request
     * @return String
     */
    public static String getNickName(HttpServletRequest request) {
        String value = getCookieValue(request, NICK_NAME);
        try {
            if (StringUtils.isNotBlank(value)) {
                return URLDecoder.decode(value, GlobalConstants.CHARACTER_ENCODING);
            } else {
                return value;
            }
        } catch (UnsupportedEncodingException e) {
            logger.error(e);
        }
        return "";
    }

    /**
     * 获取用户登录id
     * 
     * @param request
     * @return String
     */
    public static String getLoginId(HttpServletRequest request) {
        String value = getCookieValue(request, LOGIN_ID);
        try {
            if (value != null) {
                return URLDecoder.decode(value, GlobalConstants.CHARACTER_ENCODING);
            } else {
                return value;
            }
        } catch (UnsupportedEncodingException e) {
        }
        return "";
    }

    /**
     * 获取长sessionId
     * 
     * @param request
     * @return String
     */
    public static String getSessionId(HttpServletRequest request) {
        return getCookieValue(request, PER_SEEEIONID);
    }

    /**
     * 获取userType
     * 
     * @param request
     * @return String
     */
    public static String getUserType(HttpServletRequest request) {
        return getCookieValue(request, USER_TYPE);
    }

    /**
     * 获取机构
     * 
     * @param request
     * @return String
     */
    public static String getInstitution(HttpServletRequest request) {
        String value = getCookieValue(request, INSTITUTION);
        try {
            if (StringUtils.isNotBlank(value)) {
                return URLDecoder.decode(value, GlobalConstants.CHARACTER_ENCODING);
            } else {
                return value;
            }
        } catch (UnsupportedEncodingException e) {
            logger.error(e);
        }
        return "";
    }

    /**
     * 机构名称
     * 
     * @param request
     * @return
     */
    public static String getInstitutionName(HttpServletRequest request) {
        String value = getCookieValue(request, INSTITUTIONNAME);
        try {
            if (StringUtils.isNotBlank(value)) {
                return URLDecoder.decode(value, GlobalConstants.CHARACTER_ENCODING);
            } else {
                return value;
            }
        } catch (UnsupportedEncodingException e) {
            logger.error(e);
        }
        return "";
    }

    /**
     * 获取长accountno
     * 
     * @param request
     * @return String
     */
    public static String getAccountNo(HttpServletRequest request) {
        return getCookieValue(request, ACCOUNTNO);
    }

    /**
     * cookie中写值，注意与cookie的配置的key对应
     * 
     * @param request
     * @param key
     * @param value
     * @param expiry
     */
    public static void writeKey(HttpServletRequest request, String key, String value) {
        CookieModule jar = getCookieModule(request);
        if (request != null && null != jar && StringUtils.isNotBlank(value)) {
            jar.set(key, value);
        }
    }
}
